<template>
  <ElContainer class="bg-white created-activity">
    <el-main>
      <headerstepsVue
        v-bind="{ successstatus, submit, list: _list }"
      ></headerstepsVue>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="rule"
        size="default"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-tabs v-model="active" class="tabs" tab-position="left">
          <el-tab-pane lazy label="比赛基本信息" name="比赛基本信息">
            <el-row>
              <el-col :span="6">
                <el-form-item label="比赛名" prop="name">
                  <div class="el-input">
                    <el-input v-model="ruleForm.name"></el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="类型">
                  <el-select v-model="ruleForm.questiontype" disabled>
                    <el-option
                      label="公开测"
                      :value="QuestionType.PUBLIC_TEST"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="比赛时间" prop="signupstarttime">
              <el-date-picker
                v-model="startTime"
                :unlink-panels="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY/MM/DD HH:mm"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="比赛模式">
              <!-- <el-radio-group v-model="duration"> -->
              <!-- <el-radio v-model="duration" :value="false">全员统一计时</el-radio>
							<small class="text-black-50">该模式为所有人在比赛时间内进行答题，一般使用该模式</small>
							<br> -->
              <el-radio v-model="duration" :value="true">个人单独计时</el-radio>
              <small class="text-black-50"
                >所有人在比赛期间任意时间进入答题，受答题时长有限制。例如比赛持续全天，限制2小时，学生A可以从9点进入，11点交卷；学生B可以从14点进入，16点交卷</small
              >
              <!-- </el-radio-group> -->
            </el-form-item>
            <el-form-item v-show="duration" label="答题时间">
              <el-input-number
                :step="5"
                :min="0"
                :max="1200"
                step-strictly
                v-model="ruleForm.duration"
              >
              </el-input-number
              >&nbsp;分钟
            </el-form-item>
            <el-form-item label="助教老师配置">
              <el-select
                v-model="ruleForm.customerserviceid"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="v in customerservice"
                  :label="v.name"
                  :value="Number(v.ID)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="比赛说明" prop="context">
              <Wangeditor
                id="context"
                :value="context"
                ref="contexteditor"
                :zIndex="2"
                :context="htmlcontext"
              >
              </Wangeditor>
            </el-form-item>
            <el-form-item label="交卷后展示" prop="info">
              <Wangeditor
                id="info"
                :value="infoContext"
                ref="infoEditor"
                :zIndex="2"
              ></Wangeditor>
            </el-form-item>
            <div class="row">
              <div class="col text-center">
                <el-button
                  @click="submit(_list[1].title)"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，{{ _list[1].title }}</el-button
                >
              </div>
            </div>
          </el-tab-pane>
          <!-- 用户配置 -->
          <el-tab-pane lazy label="用户配置" name="用户配置">
            <el-form-item label="比赛类型" prop="type">
              <el-radio-group v-model="matchType" disabled>
                <el-radio value="public">公开比赛</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="配置激活码">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="如填写此选项，参赛者需要通过输入比赛激活码验证，如果多个激活码请用英文逗号分开"
                placement="top"
              >
                <el-input
                  placeholder="可以设置比赛激活码"
                  v-model="ruleForm.invitation"
                ></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="激活码客服" v-if="isAdmin && !tenant_id">
              <el-select
                v-model="ruleForm.info!.customerservice"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="v in customerservice"
                  :label="v.name"
                  :value="v.qrcode!"
                ></el-option>
              </el-select>
            </el-form-item>
            <div class="row m-mt-6">
              <div class="col">
                <el-button
                  @click="submit('权限配置')"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，权限配置</el-button
                >
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>
          <!-- 权限配置 -->
          <el-tab-pane lazy label="权限配置" name="权限配置">
            <el-form-item label="试卷结果展示" label-width="130px">
              <el-radio v-model="ruleForm.result" :label="3" disabled
                >交卷不展示得分</el-radio
              >
            </el-form-item>
            <div class="row m-mt-6">
              <div class="col">
                <el-button
                  @click="submit('题目配置')"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，题目配置</el-button
                >
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button
                  @click="() => submit()"
                  :loading="loading"
                  type="primary"
                  size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>
          <!-- 题目配置和分数配置保持一致 -->
          <el-tab-pane lazy label="题目配置" name="题目配置">
            <div>注： 如需导入非编程题，请通过题单导入题目。或者联系管理员</div>
            <selectquestionVue
              :isAdmin="isAdmin"
              v-model="questions"
              :teamid="teamid"
              :removeclick="removeclick"
              :addclick="addclick"
              :questionid="questions"
              index="oldid"
              :change="change"
            ></selectquestionVue>
            <div class="row m-mt-6">
              <div class="col">
                <el-button
                  @click="submit('分数配置')"
                  :style="{
                    '--el-button-bg-color': '#434343',
                    '--el-button-border-color': '#434343',
                  }"
                  size="large"
                  type="primary"
                  >下一步，分数配置</el-button
                >
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane lazy label="分数配置" name="分数配置">
            <div
              :style="{
                background: 'var(--color-f5)',
                padding: '24px',
              }"
            >
              <div
                class="container-fluid bg-white"
                :style="{
                  padding: '24px',
                }"
              >
                <div class="row m-mb-6">
                  <div class="col">已添加题目</div>
                  <div class="col text-right">
                    <span>
                      已添加:
                      <span class="text-danger">{{ questions.length }}</span
                      >题
                    </span>
                  </div>
                </div>
                <div class="row">
                  <div
                    :style="{
                      width: '80px',
                      height: '42px',
                      lineHeight: '42px',
                    }"
                  >
                    编号
                  </div>
                  <div
                    class="col"
                    :style="{ height: '42px', lineHeight: '42px' }"
                  >
                    名称
                  </div>

                  <div
                    :style="{
                      width: '90px',
                      padding: 0,
                      height: '42px',
                      lineHeight: '42px',
                    }"
                  >
                    题目类型
                  </div>
                  <div
                    :style="{
                      width: '180px',
                      padding: 0,
                      height: '42px',
                      lineHeight: '42px',
                    }"
                    class="text-center"
                  >
                    设置分值
                  </div>
                  <div
                    :style="{
                      width: '190px',
                      padding: 0,
                      height: '42px',
                      lineHeight: '42px',
                    }"
                  >
                    测试点得分设置
                  </div>
                </div>
                <hr :style="{ marginTop: '6px', marginBottom: '6px' }" />
                <div class="mydata">
                  <div
                    class="row list"
                    v-for="v in questions"
                    :key="v.oldid"
                    :style="{ marginTop: '6px', marginBottom: '6px' }"
                  >
                    <div
                      :style="{
                        width: '80px',
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      {{ v.oldid }}
                    </div>
                    <div
                      class="col text-truncate"
                      :style="{ height: '42px', lineHeight: '42px' }"
                    >
                      {{ v.name }}
                    </div>

                    <div
                      :style="{
                        width: '90px',
                        padding: 0,
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      <button
                        class="text-center"
                        type="button"
                        :style="{
                          border: 0,
                          background: 'var(--color-f5)',
                          color: 'var(--color-43)',
                          width: '78px',
                          height: '30px',
                          lineHeight: '30px',
                          fontSize: '14px',
                          cursor: 'default',
                        }"
                      >
                        <svg class="icon icon-class-var" aria-hidden="true">
                          <use :xlink:href="iconname[v.type || '代码']" />
                        </svg>
                        {{ v.type }}
                      </button>
                    </div>
                    <div
                      class="text-center"
                      :style="{
                        width: '180px',
                        padding: 0,
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      <el-input-number
                        :max="100"
                        :min="0"
                        v-model="v.score"
                      ></el-input-number>
                    </div>
                    <div
                      :style="{
                        width: '190px',
                        padding: 0,
                        height: '42px',
                        lineHeight: '42px',
                      }"
                    >
                      <el-button
                        v-show="v.type === '代码'"
                        @click="dialogVisibleindex = v.oldid || 0"
                        >测试点得分设置</el-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="row m-mt-6">
              <div class="col">
                <!-- <el-button @click="submit('权限配置')" :style="{
                  '--el-button-bg-color': '#434343',
                  '--el-button-border-color': '#434343'
                }" size="large" type="primary">下一步，权限配置</el-button> -->
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close"
                  >取消</el-button
                >
                <el-button @click="() => submit()" type="primary" size="large"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-main>
  </ElContainer>
</template>

<script setup lang="ts">
import {
  ElForm,
  ElMessage,
  UploadInstance,
  UploadRequestHandler,
  dayjs,
} from "element-plus";
import { assign } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { RouteLocationRaw, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Activity } from "../../admin/views/data";
import { activityrules } from "../../admin/views/data/formrules";
import {
  asyncgetactivity,
  asyncgetcustomerservice,
  asyncselectactivityuser,
  asyncselectmatchquestion,
} from "../../api";
import { EMstatus, Storekey } from "../../interface";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import { QuestionType } from "../../util/data";
import updateoss from "../../util/updateoss";
import selectquestionVue from "../selectquestion/index.vue";
import Wangeditor from "../wangeditor.vue";
import headerstepsVue from "./headersteps.vue";

const tenant_id = inject<string | undefined>("tenant_id", undefined);
const p = defineProps<{
  teamid?: number;
  ID?: number;
  isAdmin: boolean;
  createdorupdateactivtiy: (data: {
    data: Studycodemodel.Iactivity;
    question: Studycodemodel.Imatchquestion[];
    users: Studycodemodel.Iuser[];
    teamid?: number;
  }) => Promise<unknown>;
  routers: RouteLocationRaw;
}>();

const router = useRouter();
const route = useRoute();

type Isuccessstatus = EMstatus[];
const successstatus = ref<Isuccessstatus>([
  "finish",
  "wait",
  "wait",
  "wait",
  "wait",
]);

const iconname = {
  代码: "#icon-icon_tianjiatimu_code",
  单选: "#icon-icon_tianjiatimu_single",
  多选: "#icon-icon_tianjiatimu_multiple",
  判断: "#icon-icon_tianjiatimu_panduan",
  填空: "#icon-icon_tianjiatimu_edit",
  排序: "#icon-icon_tianjiatimu_edit",
};

const users = ref<Studycodemodel.Iuser[]>([]);
const list = [
  { title: "比赛基本信息", description: "配置比赛的基础信息" },
  { title: "用户配置", description: "参赛用户配置", isAdmin: true },
  { title: "权限配置", description: "更多比赛配置" },
  { title: "题目配置", description: "配置比赛题目内容" },
  { title: "分数配置", description: "配置比赛分数" },
];
const _list = computed(() => {
  return list.filter((c) => !c.isAdmin || c.isAdmin === p.isAdmin);
});

const getuser = computed(() => {
  return store.state.users?.rows;
});
// label
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});

const duration = ref(true);
const dialogVisibleindex = ref(0);
const dialogVisible2 = ref(false);
const loading = ref(false);

const matchquestionindex = computed<Studycodemodel.Iquestion>({
  set(e) {
    const n = questions.value.findIndex(
      (e) => e.oldid === dialogVisibleindex.value
    );
    if (n !== -1 && e) {
      const t: Studycodemodel.Imatchquestion = e;
      t.example = e.testcases;
      questions.value.splice(n, 0, e);
    }
  },
  get() {
    const data =
      questions.value.find((e) => e.oldid === dialogVisibleindex.value) || {};
    const n: Studycodemodel.Iquestion = data;
    n.testcases = data.example;
    return n;
  },
});

/**
 * 跳转
 */
async function next(num: string) {
  if (num === _list.value[0]?.title) {
    active.value = _list.value[0].title;
    successstatus.value = ["finish", "wait", "wait", "wait", "wait"];
  } else {
    rule.value?.validateField(["name"], async (a: any) => {
      if (a) {
        const _num = _list.value.findIndex((e) => e.title === num);
        active.value = _list.value[_num].title;
        if (_num === 1) {
          successstatus.value = ["success", "finish", "wait", "wait", "wait"];
        }
        if (_num === 2) {
          successstatus.value = [
            "success",
            "success",
            "finish",
            "wait",
            "wait",
          ];
        }
        if (_num === 3) {
          successstatus.value = [
            "success",
            "success",
            "success",
            "finish",
            "wait",
          ];
        }
        if (_num === 4) {
          successstatus.value = [
            "success",
            "success",
            "success",
            "success",
            "finish",
          ];
        }
        if (_num === 5) {
          successstatus.value = [
            "success",
            "success",
            "success",
            "success",
            "success",
          ];
        }
      }
    });
  }
}

watch(
  () => p.ID,
  () => {
    start();
  }
);
const filename = ref("");
const request: UploadRequestHandler = async (file) => {
  const { size } = file.file;
  if (size > 1024 * 1024 * 1024) {
    ElMessage.error("上传文件过大，最大只能上传1024MB");
    return;
  }
  const data = await updateoss([file.file]);
  ruleForm.file = data.url;
  filename.value = data.name;
  return data.url;
};

const upload = ref<UploadInstance>();

function close() {
  router.push(p.routers);
}

const rule = ref<typeof ElForm>();
const rules = activityrules;
const ruleForm = reactive<Studycodemodel.Iactivity>(
  assign({}, Activity, {
    teamid: p.teamid,
    type: "public",
    questiontype: QuestionType.PUBLIC_TEST, // 固定为公开测
    result: 3, // 不展示得分
    postSubmitContent: "", // 新增字段
    duration: 60,
  })
);
// 类型
const enum MatchType {
  LIMIT = "limit",
  PUBLIC = "public",
  TEAM = "team",
}
const matchType = ref<MatchType | undefined>(MatchType.PUBLIC);
watch(matchType, (v) => {
  ruleForm.type = v === MatchType.PUBLIC ? MatchType.PUBLIC : MatchType.LIMIT;
});

const questions = ref<Studycodemodel.Imatchquestion[]>([]);
const dialogVisible = ref(false);

function addclick(v: Studycodemodel.Iquestion) {
  const { ID, label, questionlabel = [], testcases, ...e } = v;
  if (!questions.value.find((e) => e.oldid === ID)) {
    questions.value.push({
      ...e,
      example: testcases,
      oldid: ID,
      label: questionlabel.map((e) =>
        String(store.state.label?.rows.find((z) => z.ID === e.labelid)?.name)
      ),
      score: 100,
    });
  }
}

function removeclick(index: number) {
  questions.value.splice(index, 1);
}

/**
 * 当前第几页
 */
const active = ref("比赛基本信息");
const context = ref("");
const htmlcontext = ref("");
const questionbankid = ref<number | undefined>();
const contexteditor = ref();
const infoEditor = ref();
const infoContext = ref(
  (ruleForm.info && parseInfoContext(ruleForm.info)) || ""
);

function parseInfoContext(val: any) {
  try {
    if (typeof val === "string") {
      const obj = JSON.parse(val);
      return obj?.context || "";
    }
    if (typeof val === "object" && val !== null) {
      return val.context || "";
    }
  } catch {
    return "";
  }
  return "";
}

watch(
  () => ruleForm.info,
  (v) => {
    infoContext.value = parseInfoContext(v);
  }
);

const store = useStore(Storekey);
const selectarr = ref<Studycodemodel.Iuser[]>([]);
const startTime = ref<[Date, Date]>([new Date(), new Date()]);

watch(
  () => route.query.ID,
  (v) => {
    if (v && typeof v === "number") {
      start();
      dialogVisible.value = true;
    }
  }
);

const customerservice = ref<Studycodemodel.Icustomerservice[]>([]);
onMounted(async () => {
  // 初始化
  await start();
  // 是否有团队
  customerservice.value = await asyncgetcustomerservice();
});

// 开始
async function start() {
  console.log("start", ruleForm);
  try {
    if (Number(route.query.ID)) {
      const data = await asyncgetactivity({ ID: Number(route.query.ID) });
      if (!data.info) {
        data.info = {};
      }
      Object.assign(ruleForm, data);
    } else {
      Object.assign({}, Activity, {
        teamid: p.teamid,
        type: "public",
        questiontype: QuestionType.PUBLIC_TEST, // 固定为公开测
        result: 3, // 不展示得分
        postSubmitContent: "", // 新增字段
        duration: 60,
      });
    }
    startTime.value = [
      new Date(ruleForm.activitystarttime || Date.now()),
      new Date(ruleForm.activityendtime || Date.now()),
    ];
    // duration.value = !!ruleForm.duration
    if (ruleForm.teamid) {
      await store.dispatch("actionteam", { ID: ruleForm.teamid });
    }
    context.value = ruleForm.context || "";
    htmlcontext.value = ruleForm.htmlcontext || "";
    questions.value = [];
    questionbankid.value = undefined;
    const data = ruleForm.activityuser?.map((v) =>
      v.user ? v.user : { ID: v.userid }
    ) as Studycodemodel.Iuser[];
    if (data) {
      selectarr.value = data;
    } else {
      selectarr.value = [];
    }
    if (ruleForm.ID) {
      asyncselectmatchquestion({ activityid: ruleForm.ID })
        .then(([v]) => {
          if (v) {
            questions.value = v.matchquestion || [];
          }
        })
        .catch((e: undefined) => {
          ElMessage.error(e);
        });
      asyncselectactivityuser({ activityid: ruleForm.ID })
        .then((e) => {
          users.value = e.rows.map((e) => e.user || {});
        })
        .catch(() => {});
      // 回填 新版比赛类型
      matchType.value = ruleForm?.type as MatchType | undefined;
      if (ruleForm.teamid) {
        matchType.value = MatchType.TEAM;
      }
    }
    activeName.value = "first";
  } catch (e: any) {
    ElMessage.error(e);
  }
}

function change(value: Studycodemodel.Iquestion[] = []) {
  questions.value = value;
}

const activeName = ref<"first" | "two">("first");

// 提交
async function submit(index?: string) {
  // if (index === last(_list.value)?.title) {
  //   try {
  //     await ElMessageBox.confirm("是否要自动配置题目测试点分数", "Warning", {
  //       confirmButtonText: "确定",
  //       cancelButtonText: "取消",
  //       type: "warning",
  //     })
  //     updatetestcase()
  //   } catch (e) {

  //   }
  // }
  loading.value = true;
  if (!index) {
    const context = contexteditor.value?.gethtml();
    const htmlcontext = contexteditor.value?.getcontext();
    ruleForm.context = context;
    ruleForm.htmlcontext = htmlcontext;
    // 新增：保存交卷后展示内容
    const infoVal = infoEditor.value?.gethtml?.() || infoContext.value || "";
    ruleForm.info = assign({}, ruleForm.info, { context: infoVal });
    ruleForm.duration = duration.value ? ruleForm.duration : 0;
    ruleForm.activitystarttime = startTime.value[0];
    ruleForm.activityendtime = startTime.value[1];
    ruleForm.signupstarttime = dayjs(ruleForm.activitystarttime)
      .subtract(30, "day")
      .toDate();
    ruleForm.signupendtime = ruleForm.activityendtime;
    await p.createdorupdateactivtiy({
      data: ruleForm,
      question: questions.value.map((v, k) => {
        return {
          ...v,
          paixu: k,
        };
      }),
      users: users.value,
      teamid: p.teamid,
    });

    router.push(p.routers);
  } else {
    next(index);
  }
  loading.value = false;
}

watch(
  () => dialogVisibleindex.value,
  (v) => {
    dialogVisible2.value = Boolean(v);
  }
);
watch(
  () => dialogVisible2.value,
  (v) => {
    if (!v) {
      dialogVisibleindex.value = 0;
    }
  }
);

function adduser(t: Studycodemodel.Iuser) {
  const n = users.value.find((e) => e.ID === t.ID);
  if (!n) {
    users.value.push(t);
  }
}
</script>

<style scoped>
.demo-ruleForm {
  margin-top: 24px;
}

.el-upload-list__item-thumbnail {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  text-align: center;
  line-height: 180px;
  color: rgba(0, 0, 0, 0);
}

.el-upload-list__item-thumbnail:hover div {
  color: #fff;
  background-color: rgba(31, 31, 31, 0.8);
}
</style>

<style>
.upload .el-upload-dragger {
  width: 300px !important;
  height: 180px !important;
}

.created-activity .el-form-item__content {
  display: block;
}
</style>

<style>
.created-activity .el-upload-list,
.created-activity .el-upload-list__item {
  margin: 0 !important;
}
</style>
